package com.common.www.controller.project;

import com.alibaba.fastjson.JSON;
import org.springframework.boot.base.jpa.domain.PageableRequest;
import org.springframework.boot.base.jpa.service.IBaseService;
import com.common.www.bean.entity.Result;
import com.common.www.bean.entity.Sort;
import com.common.www.bean.entity.project.Company;
import com.common.www.controller.base.DefaultCrudController;
import com.common.www.data.NetCode;
import com.common.www.service.auth.UserService;
import com.common.www.service.project.CompanyService;
import com.common.www.utils.ParamsUtils;
import com.common.www.utils.R;
import com.common.www.utils.SortUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@CrossOrigin
@RestController
@RequestMapping(value = {"mgt/company"})
@Api(tags = "MGT 公司管理接口")
public class MGTCompanyController extends DefaultCrudController<Company, Long> {
    @Autowired
    private CompanyService service;
    @Autowired
    private UserService userService;
    protected IBaseService getService() {
        return service;
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "json", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/saveByJson", method = RequestMethod.POST)
    public Result saveByJson(String json) {
        Company entity = JSON.parseObject(json, Company.class);
        ;
//        if (entity.getCreateUser() == null) {
//            entity.setCreateUser(SecurityContextHolder.getContext().getAuthentication().getName());
//        }
//        entity.setLastUpdateTime(TimeUtils.getLocalDate());

        //子类不取传过来的值，只替换父类
        List<Company> children = new ArrayList<>();
        if (entity.getId() != null) {
            Company type1 = service.findOne(entity.getId());
//            entity.setFlag(type1.getFlag());
            entity.setCreateTime(type1.getCreateTime());
            children = type1.getChildren();

            if (children != null) {
                for (Company type : children) {//修改的父类不能指向自己的子类避免进入死循环
                    if (entity.getParent() != null && entity.getParent().getId() != null
                            && type.getId() != null && entity.getParent().getId().equals(type.getId())) {
                        return null;
                    }
                }

            }
        } else {
            children = entity.getChildren();
            entity.setFlag(1);
            entity.setSort(9999);
            entity.setCreateTime(new Date());
            if (children != null)
                for (Company type :
                        children) {//修改的父类不能指向自己的子类避免进入死循环
                    if (entity.getParent() != null && entity.getParent().getId() != null
                            && type.getId() != null && entity.getParent().getId().equals(type.getId())) {
                        return null;
                    }
                }
        }
        entity.setChildren(children);
        entity = service.save(entity);
        if (entity.getParent() != null && entity.getParent().getId() != null) {
            entity.setParent(service.findOne(entity.getParent().getId()));
        } else {
            entity.setParent(null);
        }
        //存储完后分析一次所有受影响的节点路劲再重新存储一次
        entity.setNodePath(service.getNodePath(entity, ""));
        service.sortType(entity);
        service.setChildNodePath(entity.getChildren());
        service.sortChildNodePath(entity.getChildren());
        entity.setLevel(service.getTypeLevel(entity));
        entity = service.save(entity);

        return R.ok(entity);
    }

    @ApiOperation("批量删除启用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "String", defaultValue = ""),
            @ApiImplicitParam(name = "operate", value = "1.删除 2.启用", defaultValue = ""),
    })
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    public Result batchDelete(Long[] ids, Integer operate) {
        if (ParamsUtils.isInputEmpty(ids, operate)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        for (int i = 0; i < ids.length; i++) {
            Company authUser = service.findOne(ids[i]);
            if (authUser != null) {
                if (operate == 1) {
                    authUser.setFlag(0);
                } else if (operate == 2) {
                    authUser.setFlag(1);
                }
                service.save(authUser);
            }
        }
        return R.ok();
    }

    //    @Override
//    @JSON(excludeProperties = {"data.*\\.parent.*\\.children", "data.*\\.parent.*\\.parent"})
//    public Company getById(Long id) {
//        return service.getById(id);
//    }
//
    @ApiOperation(value = "逻辑删除", notes = "参数为JSON数据对象")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "long", paramType = "query"),
    })
    @RequestMapping(value = "/deleteByLogic", method = RequestMethod.POST)
    public Result deleteByLogic(Long id) {
        service.deleteById(id);
        return R.ok();
    }

    @ApiOperation(value = "逻辑删除批量", notes = "参数为JSON数据对象")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "8,28", dataType = "long", paramType = "query"),
    })
    @RequestMapping(value = "/deletesByLogic", method = RequestMethod.POST)
    public Result deletesByLogic(Long[] ids) {
        service.deleteByIds(ids);
        return R.ok();
    }


//    @ApiOperation(value = "扁平化查询所有节点", notes = "扁平化查询所有节点，所有children的节点全部放到一个列表中")
//    @RequestMapping(value = "/queryAllByFLat", method = RequestMethod.POST)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id", value = "当前节点的id，会自动排除掉与此id相关的节点", dataType = "Long", paramType = "query"),
//    })
//    @JSON(excludeProperties = {"data.*\\.parent.*\\.children", "data.*\\.parent.*\\.parent", "data.*\\.children"})
//    public Result queryAllByFLat(Long id) {
//        //查询最顶级的节点
//        String sql = "select * from project_img_type where parent is null and flag = 1 order by sort asc";
//        List<Company> list = service.getRepository().executeSqlQuery(sql, Company.class);
//
//        service.setChildNodePath(list);//生成节点路劲
//        service.sortChildNodePath(list);//重新排序节点路劲
//        List<Company> resList = new ArrayList<>();
//        service.getChildBlFlat(list, resList);//把子节点提出来放到一个列表中
//        //重新进行节点排序，父类节点排在最前面
//        Collections.sort(resList, new Comparator<Company>() {
//            @Override
//            public int compare(Company o1, Company o2) {
//                long sort1 = (o1.getParent() == null ? 0 : o1.getParent().getId());
//                long sort2 = (o2.getParent() == null ? 0 : o2.getParent().getId());
//                if (sort1 > sort2) {
//                    return 1;
//                } else {
//                    return -1;
//                }
//            }
//        });
//        Collections.sort(resList, new Comparator<Company>() {
//            @Override
//            public int compare(Company o1, Company o2) {
//                long pid1 = (o1.getParent() == null ? 0 : o1.getParent().getId());
//                long pid2 = (o2.getParent() == null ? 0 : o2.getParent().getId());
//                if (pid1 == pid2) {
//                    long sort1 = o1.getSort();
//                    long sort2 = o2.getSort();
//                    if (sort1 > sort2) {
//                        return 1;
//                    } else {
//                        return -1;
//                    }
//                } else {
//                    return 0;
//                }
//
//            }
//        });
//
//        if (id != null) {
//            Company currentType = service.findOne(id);
//            if (currentType != null) {
//                //返回的列表需要排除节点自身和所有子节点
//                List<Company> childList = new ArrayList<>();
//                service.getChildBlFlat(currentType.getChildren(), childList);//把子节点提出来放到一个列表中
//                for (int i = 0; i < resList.size(); i++) {
//                    Company projectRecordType = resList.get(i);
//                    if (projectRecordType.getId().equals(currentType.getId())) {
//                        resList.remove(i--);
//                    }
//                    for (Company projectRecordType2 :
//                            childList) {
//                        if (projectRecordType.getId().equals(projectRecordType2.getId())) {
//                            resList.remove(i--);
//                        }
//                    }
//                }
//            }
//        }
//
//        return ResultUtil.ok("请求成功", resList);
//    }

//    @JSON(excludeProperties = {"data.*\\.parent.*\\.children", "data.*\\.children"})
//    public Page query(String params, String pageable) {
//        PageableRequest pageableRequest;
//        if (!TxtUtil.isEmpty(pageable)) {//添加分类排序
//            pageableRequest = com.alibaba.fastjson.JSON.parseObject(pageable, PageableRequest.class);
//        } else {
//            pageableRequest = new PageableRequest();
//        }
//        if (pageableRequest.getSort().isUnsorted())
//            pageableRequest.setSort("[{\"direction\":\"asc\",\"property\":\"parent\"},{\"direction\":\"asc\",\"property\":\"sort\"}" +
//                    ",{\"direction\":\"desc\",\"property\":\"lastUpdateTime\"}]");
//
//        LinkedHashMap<String, Object> hashMap =
//                com.alibaba.fastjson.JSON.parseObject(params, new TypeReference<LinkedHashMap<String, Object>>() {
//                });
//        Page<Company> page = service.query(hashMap, pageableRequest);
//
//        //自动计算类型的节点地址
//        for (Company projectRecordType :
//                page.getContent()) {
//            String path = service.getNodePath(projectRecordType, "");
//            String newPath = "";
//            //路劲结果拆分后反向排序，除去第一个节点路劲(自己本身的节点)
//            String res[] = path.split("/");
//            for (int i = res.length - 1; i > 1; i--) {
//                newPath += "/" + res[i];
//            }
//            if (TxtUtil.isEmpty(newPath)) {
//                newPath += "/";
//            }
//            projectRecordType.setNodePath(newPath);
//        }
//
//        List<Company> list = new ArrayList<>();
//        list.addAll(page.getContent());
//        //重新进行节点排序，父类节点排在最前面
//        Collections.sort(list, new Comparator<Company>() {
//            @Override
//            public int compare(Company o1, Company o2) {
//                long sort1 = o1.getSort() + (o1.getParent() == null ? 0 : o1.getParent().getId());
//                long sort2 = o2.getSort() + (o2.getParent() == null ? 0 : o2.getParent().getId());
//                if (sort1 > sort2) {
//                    return 1;
//                } else {
//                    return -1;
//                }
//            }
//        });
//
//        return page;
//    }

//    @JSON(excludeProperties = {"data.*\\.parent.*\\.children", "data.*\\.children"})
//    public Page queryDistinct(String params, String pageable) {
//        PageableRequest pageableRequest;
//        if (!TxtUtil.isEmpty(pageable)) {//添加分类排序
//            pageableRequest = com.alibaba.fastjson.JSON.parseObject(pageable, PageableRequest.class);
//        } else {
//            pageableRequest = new PageableRequest();
//        }
//        if (pageableRequest.getSort().isUnsorted())
//            pageableRequest.setSort("[{\"direction\":\"asc\",\"property\":\"parent\"},{\"direction\":\"asc\",\"property\":\"sort\"}]");
//
//        LinkedHashMap<String, Object> hashMap =
//                com.alibaba.fastjson.JSON.parseObject(params, new TypeReference<LinkedHashMap<String, Object>>() {
//                });
//        Page<Company> page = service.query(hashMap, pageableRequest);
//
//        //自动计算类型的节点地址
//        for (Company projectRecordType :
//                page.getContent()) {
//            String path = service.getNodePath(projectRecordType, "");
//            String newPath = "";
//            //路劲结果拆分后反向排序，除去第一个节点路劲(自己本身的节点)
//            String res[] = path.split("/");
//            for (int i = res.length - 1; i > 1; i--) {
//                newPath += "/" + res[i];
//            }
//            if (TxtUtil.isEmpty(newPath)) {
//                newPath += "/";
//            }
//            projectRecordType.setNodePath(newPath);
//        }
//
//        List<Company> list = new ArrayList<>();
//        list.addAll(page.getContent());
//        //重新进行节点排序，父类节点排在最前面
//        Collections.sort(list, new Comparator<Company>() {
//            @Override
//            public int compare(Company o1, Company o2) {
//                long sort1 = o1.getSort() + (o1.getParent() == null ? 0 : o1.getParent().getId());
//                long sort2 = o2.getSort() + (o2.getParent() == null ? 0 : o2.getParent().getId());
//                if (sort1 > sort2) {
//                    return 1;
//                } else {
//                    return -1;
//                }
//            }
//        });
//
//        return page;
//    }

    @ApiOperation("批量更新顺序")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "originId", value = "原id"),
            @ApiImplicitParam(name = "relId", value = "变动后相对变化的id"),
            @ApiImplicitParam(name = "type", value = "变化 类型 before  after  inner"),
    })
    @RequestMapping(value = "/updateSort", method = RequestMethod.POST)
    public Result updateSort(Long originId, Long relId, String type) {
        if (ParamsUtils.isInputEmpty(originId, relId, type)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        Company originType = service.getById(originId);
        Company relType = service.getById(relId);

        if (originType == null || relType == null) {
            return R.fail("操作失败");
        }
        if ("before".equals(type) || "after".equals(type)) {
            originType.setLevel(relType.getLevel());
            originType.setParent(relType.getParent());
//            //设置排序位置
            originType.setSort(relType.getSort());
            //查询同等级下相同类型的分类列表进行一次排序
            HashMap hashMap = new HashMap();
            hashMap.put("level", relType.getLevel());
            if (relType.getParent() != null)
                hashMap.put("parent.id", relType.getParent().getId());

            PageableRequest pageableRequest = new PageableRequest();
            pageableRequest.setSort(SortUtils.addSort(new Sort("sort", "asc")));
            List<Company> list = service.getList(hashMap, pageableRequest);

            //先移除
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getId() == originType.getId()) {
                    list.remove(i--);
                }
            }

            int relIndex = 0;
            for (int i = 0; i < list.size(); i++) {
//                if (relType.getSort() == list.get(i).getSort()) {
//                    list.get(i).setSort(i);
//                }
                if (relType.getId() == list.get(i).getId()) {
                    relIndex = i;
                }
            }

            if ("before".equals(type)) {
                list.add(relIndex, originType);
            } else if ("after".equals(type)) {
                list.add(relIndex + 1, originType);
            }

            for (int i = 0; i < list.size(); i++) {
                list.get(i).setSort(i);
            }

            for (int i = 0; i < list.size(); i++) {
                System.out.println(list.get(i).getName() + "   " + list.get(i).getSort());
            }
            service.save(list);
            service.save(originType);
        } else if ("inner".equals(type)) {
            originType.setLevel(relType.getLevel() + 1);
            originType.setParent(relType);
//            //设置排序位置
            originType.setSort(relType.getSort());
            //查询同等级下相同类型的分类列表进行一次排序
            HashMap hashMap = new HashMap();
            hashMap.put("level", relType.getLevel() + 1);
            if (relType.getParent() != null)
                hashMap.put("parent.id", relType.getId());

            PageableRequest pageableRequest = new PageableRequest();
            pageableRequest.setSort(SortUtils.addSort(new Sort("sort", "asc")));
            List<Company> list = service.getList(hashMap, pageableRequest);

            //先移除
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getId() == originType.getId()) {
                    list.remove(i--);
                }
            }

            list.add(originType);

            for (int i = 0; i < list.size(); i++) {
                list.get(i).setSort(i);
            }

            for (int i = 0; i < list.size(); i++) {
                System.out.println(list.get(i).getName() + "   " + list.get(i).getSort());
            }
            service.save(list);
            service.save(originType);
        }


        Company entity = originType.getParent();
        if (entity != null) {//1级分类无需处理子分类的节点数据
            //存储完后分析一次所有受影响的节点路劲再重新存储一次
            entity.setNodePath(service.getNodePath(entity, ""));
            service.sortType(entity);
            service.setChildNodePath(entity.getChildren());
            service.sortChildNodePath(entity.getChildren());
            entity.setLevel(service.getTypeLevel(entity));
        }

        return R.ok();
    }

}

